package com.example.sunmiv1.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.GoodWarehousingAdapter;
import com.example.sunmiv1.adapter.InventoryAdapter;
import com.example.sunmiv1.adapter.InventoryInfoAdapter;
import com.example.sunmiv1.entity.InventoryInfoBean;
import com.example.sunmiv1.entity.InventoryListBean;
import com.example.sunmiv1.listener.ClickListener;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class InventoryListActivity extends Activity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.edit_inventoryList)
    EditText editInventoryList;
    @BindView(R.id.search_inventoryList)
    ImageView searchInventoryList;
    @BindView(R.id.listView_inventoryList)
    PullToRefreshListView listViewInventoryList;
    @BindView(R.id.add_inventoryList)
    Button addInventoryList;
    @BindView(R.id.close_inventoryList)
    ImageView closeInventoryList;
    @BindView(R.id.detailLv_inventoryList)
    ListView detailLvInventoryList;
    @BindView(R.id.ll_inventoryList)
    LinearLayout llInventoryList;
    @BindView(R.id.rl_inventoryList)
    LinearLayout rlInventoryList;
    @BindView(R.id.btn_to_top)
    ImageView btnToTop;

    private Context context;
    private ACache aCache;
    private LoadingDialog loadingDialog;
    private int page = 1;
    private Intent intent;
    private InventoryListBean inventoryListBean;
    private InventoryAdapter inventoryAdapter;
    private List<InventoryListBean.DataBean> list = new ArrayList<>();

    private static final String TAG = "InventoryListActivity";
    private InventoryInfoBean inventoryInfoBean;
    private InventoryInfoAdapter inventoryInfoAdapter;
    private List<InventoryInfoBean.DataBean> detailsList = new ArrayList<>();

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    for (InventoryListBean.DataBean dataBean : inventoryListBean.getData()) {
                        list.add(dataBean);
                    }
                    page++;
                    setInventoryAdapter();
                    break;
                case 2:
                    setInventoryAdapter();
                    break;
                case 3:
                    for (InventoryInfoBean.DataBean dataBean : inventoryInfoBean.getData()) {
                        detailsList.add(dataBean);
                    }
                    rlInventoryList.setVisibility(View.VISIBLE);
                    setInventoryInfoAdapter();
                    break;
                case 4:
                    setInventoryInfoAdapter();
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_inventory_list);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.inventoryListTitle);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        setInventoryAdapter();
        initListener();
    }

    private void initListener() {
        listViewInventoryList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                list.clear();
                setInventoryAdapter();
                getInventoryList();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getInventoryList();
            }
        });
        /*listViewInventoryList.setOnItemClickListener((parent, view, position, id) -> {
            detailsList.clear();
            Log.e(TAG, "initListener: position=" + position);
            getInventoryInfo(list.get(position - 1).getId());
        });*/
        inventoryAdapter.setClickListener((v, position, type) -> {
            if (type == 1) {
                if ("2".equals(list.get(position).getStatus())) {
                    Intent intent = new Intent(context, NewInventoryActivity.class);
//                intent.putStringArrayListExtra("not_in_ids", notInIdArr);
                    intent.putExtra("order_id", list.get(position).getId());
                    context.startActivity(intent);
                }
            } else {
                detailsList.clear();
                Log.e(TAG, "initListener: position=" + position);
                getInventoryInfo(list.get(position).getId());

            }
        });


    }


    @OnClick({R.id.title_back, R.id.btn_to_top, R.id.tv_start_time, R.id.tv_end_time,
            R.id.add_inventoryList, R.id.search_inventoryList,
            R.id.rl_inventoryList, R.id.close_inventoryList})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.tv_start_time:
                getDateFromDatePickerDialog(tvStartTime);
                break;
            case R.id.tv_end_time:
                getDateFromDatePickerDialog(tvEndTime);
                break;
            case R.id.add_inventoryList:
                intent = new Intent(context, NewInventoryActivity.class);
                startActivity(intent);
                break;
            case R.id.search_inventoryList:
                page = 1;
                list.clear();
                setInventoryAdapter();
                getInventoryList();
                break;
            case R.id.rl_inventoryList:
                break;
            case R.id.close_inventoryList:
                rlInventoryList.setVisibility(View.GONE);
                break;
            case R.id.btn_to_top:
                listViewInventoryList.getRefreshableView().setSelection(0);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        page = 1;
        list.clear();
        setInventoryAdapter();
        getInventoryList();
    }

    /*設置盤點列表適配器*/
    private void setInventoryAdapter() {
        if (inventoryAdapter == null) {
            inventoryAdapter = new InventoryAdapter(context, list);
            listViewInventoryList.setAdapter(inventoryAdapter);
        } else {
            inventoryAdapter.notifyDataSetChanged();
        }
    }

    private void setInventoryInfoAdapter() {
        inventoryInfoAdapter = new InventoryInfoAdapter(context, detailsList);
        detailLvInventoryList.setAdapter(inventoryInfoAdapter);
        inventoryInfoAdapter.setChoose(index -> {
            if ("1".equals(detailsList.get(index).getSerial_number_state())) {
                rlInventoryList.setVisibility(View.GONE);
                Intent intent = new Intent(context, StringCodeOperationActivity.class);
                intent.putExtra("operation", 4);
                intent.putExtra("id",detailsList.get(index).getId());
                context.startActivity(intent);
            }
        });
    }

    /*獲取盤點列表*/
    private void getInventoryList() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("page", page);
            jsonObject.put("limit", 20);
            jsonObject.put("order_number", editInventoryList.getText().toString().trim());
            jsonObject.put("start_time", tvStartTime.getText().toString().trim());
            jsonObject.put("end_time", tvEndTime.getText().toString().trim());
            HttpUtils.post(context, Common.GET_INVENTORY_LIST, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    listViewInventoryList.onRefreshComplete();
                    Gson gson = new Gson();
                    inventoryListBean = gson.fromJson(text, InventoryListBean.class);
                    Toast.makeText(context, inventoryListBean.getMsg(), Toast.LENGTH_SHORT).show();
                    Message msg = new Message();
                    if (inventoryListBean.getStatus() == 1) {
                        msg.what = 1;
                    } else {
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                    listViewInventoryList.onRefreshComplete();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*獲取盤點詳情*/
    private void getInventoryInfo(String id) {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("id", id);
            HttpUtils.post(context, Common.GET_INVENTORY_INFO, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    inventoryInfoBean = GsonUtils.JsonToBean(text, InventoryInfoBean.class);
                    Message msg = new Message();
                    if (inventoryInfoBean.getStatus() == 1) {
                        msg.what = 3;
                    } else {
                        msg.what = 4;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否則所有的組件都不會有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);

    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //獲取輸入框當前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 點擊的是輸入框區域，保留點擊EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 點擊某個textView，調起時間選擇器，設置該時間選擇器返回的時間給該textView
     *
     * @param tv textView
     */
    private void getDateFromDatePickerDialog(TextView tv) {
        Calendar calendar = Calendar.getInstance();
        new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            // 綁定監聽器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此處得到選擇的時間，可以進行你想要的操作
                if ((monthOfYear + 1) < 10) {
                    tv.setText(year + "-0" + (monthOfYear + 1) + "-" + dayOfMonth);
                } else {
                    tv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                }
            }
        }// 設置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }
}
